package com.tsfyun.common.base.util;

import com.google.common.collect.Lists;
import com.tsfyun.common.base.vo.KeyValue;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.List;

/**
 * @Description: 枚举工具类
 * @since Created in 2019/12/25 18:42
 */
@Slf4j
public class EnumUtils {

    //获取code方法名
    private static final String GET_KEY_METHOD_NAME = "getKey";

    private static final String GET_CODE_METHOD_NAME = "getCode";//找不到getValue退而求其次

    //获取name方法名
    private static final String GET_VALUE_METHOD_NAME = "getValue";

    private static final String GET_NAME_METHOD_NAME = "getName";//找不到getDesc退而求其次

    /**
     * 根据枚举类获取该枚举类下面的枚举项目
     *
     * @param clazz
     * @return
     */
    public static List<KeyValue<String, Object>> getEnumValueByClass(Class<? extends Enum> clazz) {
        List<KeyValue<String, Object>> list = Lists.newArrayList();
        KeyValue<String, Object> kv = null;
        Enum<?>[] enums = clazz.getEnumConstants();
        Method getValueMethod = null;
        Method getTextMethod = null;
        try {
            getValueMethod = clazz.getMethod(GET_VALUE_METHOD_NAME);
        } catch (Exception e) {
            try {
                getValueMethod = clazz.getMethod(GET_CODE_METHOD_NAME);
            } catch (NoSuchMethodException e1) {

            }
        }
        try {
            getTextMethod = clazz.getMethod(GET_VALUE_METHOD_NAME);
        } catch (Exception e) {
            try {
                getTextMethod = clazz.getMethod(GET_NAME_METHOD_NAME);
            } catch (NoSuchMethodException e1) {
                //仍然找不到，不再继续找
            }
        }
        for (Enum em : enums) {
            kv = new KeyValue<>();
            try {
                kv.setKey(getValueMethod.invoke(em).toString());
                kv.setValue(getTextMethod.invoke(em).toString());
                list.add(kv);
            } catch (Exception e) {
                //无此方法报错
                log.error("获取枚举数据异常", e);
            }
        }
        return list;
    }

}
